package com.blacktech.dbu.auth.service;

import com.blacktech.dbu.auth.entity.DbuUser;
import com.blacktech.dbu.auth.repository.UserProductRepository;
import com.blacktech.dbu.auth.repository.UserRepository;
import com.blacktech.dbu.core.dict.UserStatus;
import com.blacktech.dbu.core.dict.UserType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 授权服务
 *
 * @author Yanyunsong
 */
@Slf4j
@Service
public class AuthorizationService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserProductRepository userProductRepository;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        DbuUser user = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));

        // 检查账户状态
        if (!user.isEnabled()) {
            throw new UsernameNotFoundException("账户已禁用: " + username);
        }

        if (!user.isAccountNonLocked()) {
            // 检查锁定是否已过期
            if (user.isLockExpired()) {
                // 自动解锁账户
                user.setStatus(UserStatus.ENABLED);
                user.setLoginFailedCount(0);
                user.setLockedTime(null);
                userRepository.save(user);
            } else {
                throw new UsernameNotFoundException("账户已锁定: " + username);
            }
        }

        // 构建权限列表
        List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getUserType().name()));
        return User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .accountExpired(false)
                .accountLocked(!user.isAccountNonLocked())
                .credentialsExpired(false)
                .disabled(!user.isEnabled())
                .build();
    }

    /**
     * 获取当前用户
     */
    @Transactional(readOnly = true)
    public DbuUser getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return userRepository.findByUsername(username).orElse(null);
    }

    /**
     * 检查用户对指定产品是否有权限
     *
     * @param username        用户名
     * @param productId       产品ID
     * @param permissionLevel 权限等级
     * @return 如果用户具有相应权限返回true，否则返回false
     */
    public boolean hasPermission(String username, Long productId, int permissionLevel) {
        // 查找用户
        DbuUser user = userRepository.findByUsername(username).orElse(null);
        if (user == null || !user.isEnabled()) {
            return false;
        }

        // 超级管理员拥有所有权限
        if (UserType.SUPER_ADMIN == user.getUserType()) {
            log.debug("SUPER_ADMIN {} 访问产品 {} 权限检查通过", username, productId);
            return true;
        }

        // 其他用户需要满足产品权限要求
        log.debug("用户 {} 检查产品 {} {} 权限", username, productId, permissionLevel);
        // 检查用户产品权限
        return userProductRepository.hasHigherPermission(user.getId(), productId, permissionLevel);
    }
}